<?
$txt=file_get_contents('php://input');
logfile($txt,'qunar_coop_log.txt');
include_once("/var/www/html/new/com.inc.php");

function logfile($txt,$path){
	$fp = fopen($path,"a");
	flock($fp, LOCK_EX) ;
	fwrite($fp,$txt."\n");
	flock($fp, LOCK_UN);
	fclose($fp);
}

function Err_Code($errcode){
	$arr_X_code=array(101=>20027,105=>12001,107=>90005,112=>20006,115=>90007,116=>14007,119=>13009,123=>13001,130=>20005,131=>20006,133=>14009
,134=>14010,1061=>20004,1062=>20022,1065=>13007,1071=>20010,1072=>20007,1075=>13004,1077=>13005);
	$ecode=@$arr_X_code[$errcode];
	if (!$ecode) $ecode=90001;
	return $ecode;
}
function Err_Word($errcode){
	$arr_X_word=array(103=>'您选择的出行日期格式不合法',101=>'创建订单异常，用户未登陆',105=>'产品不存在，不可预订',107=>'供应商交互XML解析错误',112=>'创建订单异常，取票人手机号码异常',115=>'web服务调用错误',116=>'电子票最多重复发送5次',119=>'订单状态不正确，不能重新发送入园凭证',123=>'订单不存在',130=>'创建订单异常，取票人邮箱格式不合法',131=>'创建订单异常，取票人手机号码异常',133=>'订单消费失败，订单还未到有效使用日期',134=>'订单消费失败，订单已超过有效使用日期',1061=>'创建订单异常，选购产品不存在',1062=>'创建订单异常，库存不足',1065=>'订单产品价格信息异常',1071=>'创建订单异常，出行日期为空',1072=>'创建订单异常，取票人姓名异常',1075=>'订单存在，但不属于该用户',1077=>'该订单无法修改');
	$eword=@$arr_X_word[$errcode];
	if (!$eword) $eword='其他错误';
	return $eword;
}
function Arr_aid($supplierIdentity){
	 $Identity=array('FUJIANXIANXING=' =>4,'MORUISHUISHIJIE' =>1057,'GULONGSHAN' =>2445);
	 $eword=@$Identity[$supplierIdentity];
	 return $eword;
	 }

//初始化数据
$s1=new SoapClient("http://open.12301.cc/openService/MXSE.wsdl",array('encoding' =>'UTF-8','cache_wsdl' => 0));
$ac='123492';
$pw='b4b55c7adcff5bdbc3d5a969e85cb8b2';
$nowdate=date("Y-m-d H:i:s");
// $supplierIdentity='MORUISHUISHIJIE';//魔锐水世界
// $signkey='TU9SVUlTSFVJU0hJSklF';//魔锐水世界

/* identity：FUJIANXIANXING
signkey：RlVKSUFOWElBTlhJTkc= 
supplierIdentity： GULONGSHAN
signkey： R1VMT05HU0hBTg
*/
$arr_supplier=array('FUJIANXIANXING'=>'RlVKSUFOWElBTlhJTkc=','GULONGSHAN'=>'R1VMT05HU0hBTg','MORUISHUISHIJIE'=>'TU9SVUlTSFVJU0hJSklF','landiaoxyc'=>'bGFuZGlhb3h5Yw==','YYTX'=>'WVlUWA==','DEBUGSUPPLIER'=>'DEBUGSINGKEY');

$txt = 'method=getProductByQunar&requestParam=%7B%22data%22%3A%22PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9InllcyI%2FPjxyZXF1ZXN0IHhtbG5zPSJodHRwOi8vcGlhby5xdW5hci5jb20vMjAxMy9RTWVucGlhb1JlcXVlc3RTY2hlbWEiPjxoZWFkZXI%2BPGFwcGxpY2F0aW9uPlF1bmFyLk1lbnBpYW8uQWdlbnQuQXV0b1Rlc3Q8L2FwcGxpY2F0aW9uPjxwcm9jZXNzb3I%2BU3VwcGxpZXJEYXRhRXhjaGFuZ2VQcm9jZXNzb3I8L3Byb2Nlc3Nvcj48dmVyc2lvbj52Mi4wLjA8L3ZlcnNpb24%2BPGJvZHlUeXBlPkdldFByb2R1Y3RCeVF1bmFyUmVxdWVzdEJvZHk8L2JvZHlUeXBlPjxjcmVhdGVVc2VyPlF1bmFyLk1lbnBpYW8uQWdlbnQuQXV0b1Rlc3Q8L2NyZWF0ZVVzZXI%2BPGNyZWF0ZVRpbWU%2BMjAxNC0wOS0xNiAxNjowNDoxMjwvY3JlYXRlVGltZT48c3VwcGxpZXJJZGVudGl0eT5ERUJVR1NVUFBMSUVSPC9zdXBwbGllcklkZW50aXR5PjwvaGVhZGVyPjxib2R5IHhzaTp0eXBlPSJHZXRQcm9kdWN0QnlRdW5hclJlcXVlc3RCb2R5IiB4bWxuczp4c2k9Imh0dHA6Ly93d3cudzMub3JnLzIwMDEvWE1MU2NoZW1hLWluc3RhbmNlIj48bWV0aG9kPlNJTkdMRTwvbWV0aG9kPjxjdXJyZW50UGFnZT4xPC9jdXJyZW50UGFnZT48cGFnZVNpemU%2BMTA8L3BhZ2VTaXplPjxyZXNvdXJjZUlkPjU1ODJfMTEzPC9yZXNvdXJjZUlkPjwvYm9keT48L3JlcXVlc3Q%2B%22%2C%22securityType%22%3A%22MD5%22%2C%22signed%22%3A%2209F2308A712FE5FDA1DB272855DB5A9A%22%7D';
	

parse_str($txt,$arr);

if ($arr['method']=='getProductByQunar') {
//产品信息
    $rt=$arr['requestParam'];
	$arr1=json_decode($rt);
	$xml=base64_decode($arr1->data);
	$c=simpleXML_load_string($xml);
	$supplierIdentity=$c->header->supplierIdentity;
	$signkey=@$arr_supplier["$supplierIdentity"];	
	
	$method = $c->body->method; //方法
	$currentPage =$c->body->currentPage;// 当前页数
	$pageSize = $c->body->pageSize; //每页记录数
	$tids=$c->body->resourceId;
	$a_tids=explode('_',$tids);
	$tid=$a_tids[0]; //门票id
	$aid = $a_tids[1]; //供应商id
	
	if($method == 'SINGLE') //获取单个产品信息
	{
		$Ticket_List = $s1->__soapCall("Get_Ticket_List",array("ac"=>$ac,"pw"=>$pw,"in0"=>"","in1"=>$tid));
		$Ticket_List_xml =simpleXML_load_string($Ticket_List);
		$count = 1; //供应商的分销产量
		$resourceId = $tid; //供应商产品id
		$lid = (string)$Ticket_List_xml->Rec->UUlid;
		$Get_ScenicSpot_Info = $s1->__soapCall("Get_ScenicSpot_Info",array("ac"=>$ac,"pw"=>$pw,"in0"=>$lid));
		$Get_ScenicSpot_Info_xml =simpleXML_load_string($Get_ScenicSpot_Info);
		$productName = $Ticket_List_xml->Rec->UUtitle; //产品名称
		$sightName = $Get_ScenicSpot_Info_xml->Rec->UUtitle;//景区名称
		$City =  $Get_ScenicSpot_Info_xml->Rec->UUaddress; //目的地
		$str="select * from uu_jq_ticket where id='$tid' limit 1";	
		$GLOBALS['le']->query($str);
		$GLOBALS['le']->fetch_assoc();
		$pay=$GLOBALS['le']->f('pay');
		if($pay == 1) $paymentType = 'PREPAY'; elseif($pay == 2) $paymentType ='CASHPAY'; //支付方式 1在线支付 2景区账号支付 
 		if($Ticket_List_xml->Rec->UUdelaydays == 0) $validType = 'USE_DATE' ; //当天有效
		else $validType ='BETWEEN_USE_DATE_AND_N_DAYSAFTER';    //多少天内有效
		if($validType ='BETWEEN_USE_DATE_AND_N_DAYSAFTER')
		$daysAfterUseDaeValid = $Ticket_List_xml->Rec->UUdelaydays; //游客选定的游玩日期起x天内有效
		$useDate =date('Y-m-d'); //未知，暂留
		$marketPrice =$GLOBALS['le']->f('tprice')*100;//票面价
		$sellstock = '无限';
		$uupid = (string)$Ticket_List_xml->Rec->UUpid;
		$get_gy_price = $s1->__soapCall("Dynamic_Price_And_Storage",array("ac"=>$ac,"pw"=>$pw,"in0"=>$uupid,"in1"=>date('Y-m-d'),"in2"=>1,"in3"=>0,"in4"=>"0","in5"=>$aid));
		$get_gy_price_xml =simpleXML_load_string($get_gy_price);
		print_r($get_gy_price_xml);exit;
		$sellPrice = $get_gy_price_xml->Rec->UUsprice; //qunar供应价
		$remind = $GLOBALS['le']->f('getaddr');
		$smsTemplet ='您将会在3-5分钟内收到电子票，在景区售票处取票入园。';
		$eticketType = 'S_STRING';		
	}elseif($method == 'ALL')//获取全部产品信息
	{
		$aid = Arr_aid((string)$supplierIdentity);
		
	}
	
$string=<<<XML
<?xml version="1.0" encoding="UTF-8"?>
<response xsi:schemaLocation="http://piao.qunar.com/2013/QMenpiaoResponseSchema QMResponseDataSchema-2.0.1.xsd" xmlns="http://piao.qunar.com/2013/QMenpiaoResponseSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	<header>
		<application>Qunar.Menpiao.Agent</application>
		<processor>SupplierDataExchangeProcessor</processor>
		<version>v2.0.1</version>
		<bodyType>GetProductByQunarResponseBody</bodyType>
		<createUser>SupplierSystemName</createUser>
		<createTime>yyyy-MM-dd HH:mm:ss</createTime>
		<code>1000</code>
		<describe>成功</describe>
	</header>
	<body xsi:type="GetProductByQunarResponseBody">
		<count>$count</count>   
		<productInfos>
				<productInfo>
					<baseInfo>
						<resourceId>$tids</resourceId>  
						<sights>
							<sight>
								<sightName>$sightName</sightName> 
								<sightAddress></sightAddress>
								<city>$City</city>
								<sightlon></sightlon>
								<sightlat></sightlat>
							</sight>
						</sights>
						<productName>$productName</productName>   
					</baseInfo>
					<bookConfig>
						<paymentType>$paymentType</paymentType>
						<advanceOption>
							<bookAdvanceDay></bookAdvanceDay>
							<bookAdvanceTime></bookAdvanceTime>
							<useAdvanceHour></useAdvanceHour>
						</advanceOption>
						<autoCancelTime></autoCancelTime>
						<contactPersonRequired>
							<nameRequired></nameRequired>
							<namePinyinRequired></namePinyinRequired>
							<emailRequired></emailRequired>
							<addressRequired></addressRequired>
						</contactPersonRequired>
						<bookPersonType></bookPersonType>
						<visitPersonRequiredForQuantity></visitPersonRequiredForQuantity>
						<visitPersonRequired>
							<nameRequired></nameRequired>
							<namePinYinRequired></namePinYinRequired>
							<credentialsRequired></credentialsRequired>
							<credentialsRequiredTypes></credentialsRequiredTypes>
							<userRequiredDefined1></userRequiredDefined1>
							<userRequiredDefined2></userRequiredDefined2>
						</visitPersonRequired>
						<perPhoneMaximum></perPhoneMaximum>
						<perPhoneMaximumType></perPhoneMaximumType>
					</bookConfig>
					<priceConfig>
						<validType>$validType</validType>
						<daysAfterUseDateValid>$daysAfterUseDaeValid</daysAfterUseDateValid>
						<daysAfterBookDateValid></daysAfterBookDateValid>
						<dayUseTimePeriod></dayUseTimePeriod>						
						<calendarPrices>
							<calendarPrice>
								<useDate>$useDate</useDate>
								<marketPrice>100</marketPrice>
								<sellPrice>100</sellPrice>
								<sellstock></sellstock>
								<minimum></minimum>
								<maximum></maximum>
							</calendarPrice>
						</calendarPrices>
						<periodPrice>
							<periodStart></periodStart>
							<periodEnd></periodEnd>
							<validWeek></validWeek>
							<invalidDate></invalidDate>
							<marketPrice>100</marketPrice>
							<sellPrice>100</sellPrice>
							<sellstock></sellstock>
							<minimum></minimum>
							<maximum></maximum>
						</periodPrice>
					</priceConfig>
					<promoteConfig>
						<cashBackMoney></cashBackMoney>
					</promoteConfig>
					<productDescription>
						<feeInfo></feeInfo>
						<feeInclude></feeInclude>
						<feeExclude></feeExclude>
						<pickupTime></pickupTime>
						<pickupAddress></pickupAddress>
						<remind>$remind</remind>
						<refundOption>
							<canRefund></canRefund>
							<refundApplyTimeBeforeValidEndDay></refundApplyTimeBeforeValidEndDay>
							<refundChargeType></refundChargeType>
							<refundCharge></refundCharge>
							<refundInfo></refundInfo>
						</refundOption>
					</productDescription>
					<otherConfig>
						<telephone></telephone>
						<salePeriods>
							<salePeriod>
								<saleStartTime></saleStartTime>
								<saleEndTime></saleEndTime>
							</salePeriod>
						</salePeriods>
						<smsTemplet>$smsTemplet</smsTemplet>
						<eticketType>$eticketType</eticketType>
					</otherConfig>
				</productInfo>
		</productInfos>
	</body>
</response>
XML;

 	$bstr=base64_encode($string);

	$signed=strtoupper(md5($signkey.$bstr));

	$arr=array('data'=>$bstr,'signed'=>$signed,'securityType'=>'MD5');
	echo json_encode($arr);
	
	}elseif ($arr['method']=='createOrderForAfterPaySync' || $_REQUEST['testI']=='test')  {
//下单接口 123492  | b4b55c7adcff5bdbc3d5a969e85cb8b2 | 去哪儿 
//这里需要下单程序

	$rt=$arr['requestParam'];
	$arr1=json_decode($rt);
	$xml=base64_decode($arr1->data);
	$c=simpleXML_load_string($xml);
	$supplierIdentity=$c->header->supplierIdentity;
	$signkey=@$arr_supplier["$supplierIdentity"];	
	
	$tids=$c->body->orderInfo->product->resourceId;
	$a_tids=explode('_',$tids);
	$tid=$a_tids[0];
	
	$tid=$tid?$tid:206;//这行测试
	$remotenum=$c->body->orderInfo->orderId;
	$tprice=$c->body->orderInfo->product->sellPrice;
	$tnum=$c->body->orderInfo->orderQuantity;
	$playtime=$c->body->orderInfo->product->visitDate;
	$ordername=$c->body->orderInfo->contactPerson->name;
	$ordertel=$c->body->orderInfo->contactPerson->mobile;
	//供应商ID需要获取
	$aid=$a_tids[1];
	$aid=$aid?$aid:2;//临时
	$remotenum=$remotenum?$remotenum:'123';//临时
	$tprice=$tprice?$tprice:400;//临时
	$tnum=$tnum?$tnum:2;//临时
	$playtime=$playtime?$playtime:'2014-06-25';//临时
	$ordername=$ordername?$ordername:'test123';//临时
	$ordertel=$ordertel?$ordertel:'15959110796';//临时
	
	$str="select landid from uu_jq_ticket where id='$tid' limit 1";	
	$GLOBALS['le']->query($str);
	$GLOBALS['le']->fetch_assoc();
	$lid=$GLOBALS['le']->f('landid');



	$arr_data=array("ac"=>$ac,"pw"=>$pw,"in0"=>$lid,"in1"=>$tid,"in2"=>$remotenum,"in3"=>$tprice,"in4"=>$tnum,"in5"=>$playtime,"in6"=>$ordername,"in7"=>$ordertel,"in8"=>"","in9"=>0,"in10"=>2,"in11"=>0,"in12"=>"","in13"=>"","in14"=>0,"in15"=>0,"in16"=>$aid);
	
	$code="";
	$ordern="";
	$describe="";
	$cxml=$s1->__soapCall("PFT_Order_Submit",$arr_data);
	$cx=simpleXML_load_string($cxml);
	if ($cx->Rec->UUerrorcode){
		$txt_json=json_encode($arr_data);
		$txt_json.='|'.$cx->Rec->UUerrorcode;
		logfile($txt_json,'coop_qunar_error.txt');		
		$orderStatus='PREPAY_ORDER_PRINT_FAILED';
		$code=Err_Code($cx->Rec->UUerrorcode);
		$describe=Err_Word($cx->Rec->UUerrorcode);
	}else{
	//成功
		$code=1000;
		$ordern=$cx->Rec->UUordernum;
		$orderStatus='PREPAY_ORDER_PRINT_SUCCESS';
		$describe='成功';
	}
	
$string=<<<XML
<?xml version="1.0" encoding="UTF-8"?>
<!--Sample XML file generated by XMLSpy v2013 (http://www.altova.com)-->
<response xsi:schemaLocation="http://piao.qunar.com/2013/QMenpiaoResponseSchema QMResponseDataSchema-2.0.1.xsd" xmlns="http://piao.qunar.com/2013/QMenpiaoResponseSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	<header>
		<application>Qunar.Menpiao.Agent</application>
		<processor>SupplierDataExchangeProcessor</processor>
		<version>v2.0.1</version>
		<bodyType>CreateOrderForAfterPaySyncResponseBody</bodyType>
		<createUser>$supplierIdentity</createUser>
		<createTime>$nowdate</createTime>
		<code>$code</code>
		<describe>$describe</describe>
	</header>
	<body xsi:type="CreateOrderForAfterPaySyncResponseBody">
		<orderInfo>
			<partnerorderId>$ordern</partnerorderId>
			<orderStatus>$orderStatus</orderStatus>
		</orderInfo>
	</body>
</response>
XML;

	$bstr=base64_encode($string);

	$signed=strtoupper(md5($signkey.$bstr));

	$arr=array('data'=>$bstr,'signed'=>$signed,'securityType'=>'MD5');
	echo json_encode($arr);

}elseif ($arr['method']=='sendOrderEticket')
{   
 //重发码接口
	$rt=$arr['requestParam'];
	$arr1=json_decode($rt);
	$xml=base64_decode($arr1->data);
	$c=simpleXML_load_string($xml);
	$supplierIdentity=$c->header->supplierIdentity;
	$signkey=@$arr_supplier["$supplierIdentity"];	
    
    $ordern=(string)$c->body->orderInfo->partnerOrderId;

     //重发码
     $resend_array = array("ac"=>$ac,"pw"=>$pw,"in0"=>$ordern);
	 $resend_sms = $s1->__soapCall("reSend_SMS_Global_PL",$resend_array);
	 $resend_xml= simplexml_load_string($resend_sms);
	 if ($resend_xml->Rec->UUerrorcode){
           	$txt_json=json_encode($resend_array);
			$txt_json.='|'.$resend_xml->Rec->UUerrorcode;
			logfile($txt_json,'coop_qunar_error.txt');		
			$code=Err_Code($cx->Rec->UUerrorcode);
			$describe=Err_Word($cx->Rec->UUerrorcode);
		}else{
		//成功
			$code=1000;
			$describe='成功';
		}
        
$string=<<<XML
<?xml version="1.0" encoding="UTF-8"?>
<!--Sample XML file generated by XMLSpy v2013 (http://www.altova.com)-->
<response xsi:schemaLocation="http://piao.qunar.com/2013/QMenpiaoResponseSchema QMResponseDataSchema-2.0.1.xsd" xmlns="http://piao.qunar.com/2013/QMenpiaoResponseSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	<header>
		<application>Qunar.Menpiao.Agent</application>
		<processor>SupplierDataExchangeProcessor</processor>
		<version>v2.0.1</version>
		<bodyType>SendOrderEticketResponseBody</bodyType>
		<createUser>$supplierIdentity</createUser>
		<createTime>$nowdate</createTime>
		<code>$code</code>
		<describe>$describe</describe>
	</header>
	<body xsi:type="SendOrderEticketResponseBody">
		<message></message>
	</body>
</response>
XML;

		$bstr=base64_encode($string);
	
		$signed=strtoupper(md5($signkey.$bstr));
	
		$arr=array('data'=>$bstr,'signed'=>$signed,'securityType'=>'MD5');
		echo json_encode($arr);

}elseif ($arr['method']=='noticeOrderRefundedByQunar')
{
//这里是撤改接口
	$rt=$arr['requestParam'];
	$arr1=json_decode($rt);
	$xml=base64_decode($arr1->data);
	$c=simpleXML_load_string($xml);
	$supplierIdentity=$c->header->supplierIdentity;
	$signkey=@$arr_supplier["$supplierIdentity"];
	
	$ordern=$c->body->orderInfo->partnerorderId;
	$tnum=$c->body->orderInfo->orderQuantity;
	$rnum=$c->body->orderInfo->refundQuantity;
	$refundSeq=$c->body->orderInfo->refundSeq;
	
	//查询是否有修改记录
	$str="select refundSeq,tnum from pft_coop_qunar_record where orderid='$ordern' and status=0 and dtype=0 order by id desc limit 1";	
	$GLOBALS['le']->query($str);
	$GLOBALS['le']->fetch_assoc();
	$refundSeq_r=$GLOBALS['le']->f('refundSeq');
	$tnum_r=$GLOBALS['le']->f('tnum');
	$tnum=($tnum_r)?$tnum_r:$tnum;
	
	$rnum=($rnum==0)?$tnum:$rnum;
	$num=$tnum-$rnum;
	
	if ($refundSeq!=$refundSeq_r){
		$arr_data=array("ac"=>$ac,"pw"=>$pw,"in0"=>$ordern,"in1"=>$num);
		$cxml=$s1->__soapCall("Order_Change_Pro",$arr_data);
		$cx=simpleXML_load_string($cxml);
		if ($cx->Rec->UUerrorcode){
			$txt_json=json_encode($arr_data);
			$txt_json.='|'.$cx->Rec->UUerrorcode;
			logfile($txt_json,'coop_qunar_error.txt');		
			$code=Err_Code($cx->Rec->UUerrorcode);
			$describe=Err_Word($cx->Rec->UUerrorcode);
		}else{
		//成功
			$code=1000;
			$describe='成功';
			//修改成功记录
			$str="insert pft_coop_qunar_record set orderid='$ordern',refundSeq='$refundSeq',tnum=$num,rnum=$rnum";
			$GLOBALS['le']->query($str);
		}
	
$string=<<<XML
<?xml version="1.0" encoding="UTF-8"?>
<response xsi:schemaLocation="http://piao.qunar.com/2013/QMenpiaoResponseSchema QMResponseDataSchema-2.0.1.xsd" xmlns="http://piao.qunar.com/2013/QMenpiaoResponseSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	<header>
		<application>Qunar.Menpiao.Agent</application>
		<processor>SupplierDataExchangeProcessor</processor>
		<version>v2.0.1</version>
		<bodyType>NoticeOrderRefundedByQunarResponseBody</bodyType>
		<createUser>$supplierIdentity</createUser>
		<createTime>$nowdate</createTime>
		<code>$code</code>
		<describe>$describe</describe>
	</header>
	<body xsi:type="NoticeOrderRefundedByQunarResponseBody">
		<message></message>
	</body>
</response>
XML;

		$bstr=base64_encode($string);
	
		$signed=strtoupper(md5($signkey.$bstr));
	
		$arr=array('data'=>$bstr,'signed'=>$signed,'securityType'=>'MD5');
		echo json_encode($arr);
	}
}
elseif ($arr['method']=='testAlive')
{
//心跳检测
	echo 'alive';
}


/* echo $string;
{
"data":"data"
"signed":"signed"
"securityType":"MD5"
}

 */
?>
